<template>
  <view class="task-list-page">
    <!-- 顶部适配安全区 -->
    <up-status-bar></up-status-bar>
    <!-- 任务分类标签 -->
    <up-sticky bgColor="#fff" offset-top="0">
      <up-tabs
        :list="categoryList" 
        :current="currentCategory"
        :scrollable="true"
        @change="handleCategoryChange"
        activeStyle="color: #409eff;"
        lineColor="#409eff"
      ></up-tabs>
    </up-sticky>
    
    <!-- 任务筛选器 -->
    <view class="task-filter">
      <up-dropdown 
        active-color="#409eff"
        inactive-color="#999999"
        duration="500"
        title-size="14px"
        border-radius="10px"
        ref="uDropdownRef"
        @open="taskFilterOpen" @close="taskFilterClose"
      >
      	<up-dropdown-item v-model="sortValue" :title="sortName" :options="sortList" @change="handleSortChange"></up-dropdown-item>
			  <up-dropdown-item v-model="rewardValue" :title="rewardName" :options="rewardList" @change="handleRewardChange"></up-dropdown-item>
      </up-dropdown>
      <up-button :disabled="sortValue === 'newest' && rewardValue === '-1'" style="width: 20vw" type="primary" size="small" :plain="false" icon="close" @click="handleClearFilter">清除筛选</up-button>
    </view>
    
    <!-- 任务列表 -->
    <view class="task-list" v-if="tasks.length > 0">
      <task-card 
        v-for="task in tasks" 
        :key="task.id" 
        :task="task"
        @detail="navigateToDetail(task.id)"
        @accept="handleClaimTask(task.id)"
        @submit="navigateToSubmit(task.id)"
        @loginRequired="showLoginModal = true"
      ></task-card>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else-if="!loading">
      <up-icon customPrefix="iconfont" name="wushuju" size="80" color="#cccccc" style="justify-content: center;"></up-icon>
      <text class="empty-text">暂无任务</text>
      <text class="empty-subtext" v-if="searchKeyword">换个关键词试试吧</text>
      <text class="empty-subtext" v-else>下拉刷新试试</text>
    </view>
    
    <!-- 加载中 -->
    <u-loading-icon
      v-if="loading && tasks.length === 0" 
      text="加载中..."
      color="#409eff"
    ></u-loading-icon>
    
    <!-- 下拉刷新 -->
    <u-pull-refresh 
      v-model="refreshing"
      @refresh="handleRefresh"
      head-height="60"
      success-text="刷新成功"
    ></u-pull-refresh>
    
    <!-- 上拉加载 -->
    <u-loadmore 
      :status="loadStatus" 
      :load-text="loadText"
      @loadmore="handleLoadmore"
      v-if="hasMore"
    ></u-loadmore>
    
    <!-- 底部提示 -->
    <view class="bottom-tip" v-if="tasks.length > 0 && !hasMore">
      已经到底了
    </view>
    
    <!-- 登录弹窗 -->
    <login-modal 
      v-model:visible="showLoginModal" 
      @loginSuccess="handleLoginSuccess"
    ></login-modal>
    
    <!-- 任务领取结果提示 -->
    <u-toast ref="taskToast" />
  </view>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted } from 'vue';
import { useTaskStore } from '../../store/task.js';
import { useUserStore } from '../../store/user.js';
import TaskCard from '../../components/task-card.vue';
import LoginModal from '../../components/login-modal.vue';

export default defineComponent({
  name: 'TaskList',
  components: {
    TaskCard,
    LoginModal
  },
  setup() {
    const taskStore = useTaskStore();
    const userStore = useUserStore();
    
    // 状态管理
    const searchKeyword = ref('');
    const currentCategory = ref(0);
    const refreshing = ref(false);
    const loading = ref(true);
    const loadStatus = ref('loadmore');
    const loadText = ref('');
    const page = ref(1);
    const pageSize = ref(10);
    const hasMore = ref(true);
    const showLoginModal = ref(false);
    
    // 筛选条件
    const sortName = ref('最新发布');
    const rewardName = ref('奖励范围');
    const sortValue = ref('newest');
    const rewardValue = ref('');
    
    // 分类列表
    const categoryList = reactive([
      { name: '全部任务' },
      { name: '新手任务' },
      { name: '每日任务' },
      { name: '长期任务' },
      { name: '分享任务' },
      { name: '调查任务' }
    ]);
    
    // 排序选项
    const sortList = reactive([
      { label: '最新发布', value: 'newest' },
      { label: '奖励最高', value: 'highest_reward' },
      { label: '最简单', value: 'easiest' },
      { label: '最热门', value: 'hottest' }
    ]);
    
    // 奖励范围选项
    const rewardList = reactive([
      { label: '不限', value: '-1' },
      { label: '5-10积分', value: '5-10' },
      { label: '10-20积分', value: '10-20' },
      { label: '20-50积分', value: '20-50' },
      { label: '50+积分', value: '50+' }
    ]);
    
    // 获取任务列表
    const tasks = computed(() => taskStore.taskList);
    
    // 加载任务数据
    const loadTasks = async (isRefresh = false) => {
      if (isRefresh) {
        page.value = 1;
        hasMore.value = true;
        taskStore.setTaskList([]);
      }
      
      if (!hasMore.value) return;
      
      try {
        loading.value = page.value === 1;
        
        const params = {
        page: page.value,
        pageSize: pageSize.value,
        keyword: searchKeyword.value,
        category: currentCategory.value === 0 ? '' : categoryList[currentCategory.value].name,
        sort: sortValue.value,
        rewardRange: rewardValue.value === '-1' || rewardValue.value === '' ? '' : rewardValue.value
      };

      console.log('loadTasks params:', params);
        
      const result = await taskStore.fetchTaskList(params);
      
      if (result && result.data) {
        if (result.data.length < pageSize.value) {
          hasMore.value = false;
        }
        page.value++;
      } else {
        hasMore.value = false;
      }
      } catch (error) {
        console.error('加载任务列表失败:', error);
      } finally {
        loading.value = false;
        refreshing.value = false;
      }
    };
    
    // 处理搜索
    const handleSearch = debounce(() => {
      loadTasks(true);
    }, 500);
    
    // 清除搜索
    const clearSearch = () => {
      searchKeyword.value = '';
      loadTasks(true);
    };
    
    // 处理分类切换
    const handleCategoryChange = (tabItem) => {
      console.log('handleCategoryChange tabItem:', tabItem);
      currentCategory.value = tabItem.index;
      loadTasks(true);
    };

    // 任务筛选器打开时的处理
    const taskFilterOpen = (index) => {
      console.log('任务筛选器打开', index);
    };
    
    // 任务筛选器关闭时的处理
    const taskFilterClose = (index) => {
      console.log('任务筛选器关闭', index);
    };
    
    // 处理排序切换
    const handleSortChange = (value) => {
      console.log('handleSortChange value:', value);
      const sortItem = sortList.find(item => item.value === value);
      sortName.value = sortItem.label;
      sortValue.value = sortItem.value;
      loadTasks(true);
    };

    // 处理奖励范围切换
    const handleRewardChange = (value) => {
      console.log('handleRewardChange value:', value);
      const rewardItem = rewardList.find(item => item.value === value);
      rewardName.value = rewardItem.label;
      rewardValue.value = rewardItem.value;
      loadTasks(true);
    };
    
    // 清除所有筛选条件
    const handleClearFilter = () => {
      sortName.value = '最新发布';
      sortValue.value = 'newest';
      rewardName.value = '不限';
      rewardValue.value = '-1';
      loadTasks(true);
    };

    // 下拉刷新
    const handleRefresh = () => {
      refreshing.value = true;
      loadTasks(true);
    };
    
    // 上拉加载更多
    const handleLoadmore = () => {
      if (loading.value || !hasMore.value) return;
      loadStatus.value = 'loading';
      loadText.value = '加载中...';
      
      loadTasks().then(() => {
        if (!hasMore.value) {
          loadStatus.value = 'nomore';
          loadText.value = '没有更多数据了';
        } else {
          loadStatus.value = 'loadmore';
          loadText.value = '上拉加载更多';
        }
      });
    };
    
    // 导航到任务详情
    const navigateToDetail = (taskId) => {
      console.log('task-list navigateToDetail taskId:', taskId);
      uni.navigateTo({
        url: `/pages/task-detail/task-detail?id=${taskId}`
      });
    };
    
    // 导航到任务提交
    const navigateToSubmit = (taskId) => {
      // 检查登录状态
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
        return;
      }
      
      uni.navigateTo({
        url: `/pages/task-submit/task-submit?id=${taskId}`
      });
    };
    
    // 处理任务领取
    const handleClaimTask = async (taskId) => {
      // 检查登录状态
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
        return;
      }
      
      try {
        const result = await taskStore.claimTask(taskId);
        if (result && result.success) {
          // 显示成功提示
          uni.showToast({
            title: '领取成功',
            icon: 'success'
          });
          // 刷新任务列表
          loadTasks(true);
        } else {
          uni.showToast({
            title: result.message || '领取失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '领取失败，请稍后重试',
          icon: 'none'
        });
      }
    };
    
    // 处理登录成功
    const handleLoginSuccess = () => {
      showLoginModal.value = false;
      // 刷新任务列表，显示用户相关状态
      loadTasks(true);
    };
    
    // 防抖函数
    function debounce(fn, delay) {
      let timer = null;
      return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(context, args);
        }, delay);
      };
    }
    
    // 生命周期
    onMounted(() => {
      loadTasks();
    });
    
    return {
      searchKeyword,
      currentCategory,
      categoryList,
      sortList,
      rewardList,
      sortName,
      sortValue,
      rewardName,
      rewardValue,  
      tasks,
      refreshing,
      loading,
      loadStatus,
      loadText,
      hasMore,
      showLoginModal,
      handleSearch,
      clearSearch,
      handleCategoryChange,
      taskFilterOpen,
      taskFilterClose,
      handleSortChange,
      handleRewardChange,
      handleClearFilter,
      handleRefresh,
      handleLoadmore,
      navigateToDetail,
      navigateToSubmit,
      handleClaimTask,
      handleLoginSuccess
    };
  }
});
</script>

<style lang="scss" scoped>
.task-list-page {
  padding: 0 16px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.task-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  
  .filter-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666666;
    padding: 4px 8px;
    
    text {
      margin-right: 4px;
    }
  }
}

.task-list {
  .task-card {
    margin-bottom: 16px;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  
  .empty-text {
    display: block;
    font-size: 16px;
    color: #666666;
    margin-top: 16px;
  }
  
  .empty-subtext {
    display: block;
    font-size: 14px;
    color: #999999;
    margin-top: 8px;
  }
}

.bottom-tip {
  text-align: center;
  font-size: 12px;
  color: #999999;
  padding: 16px 0;
}
</style>